﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
using System.Threading;
using mshtml;
using AtfutureCustom;
using System.IO;

namespace AtfutureCodeMachine
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class FormMain : Form
    {
        /// <summary>
        /// 内部网站
        /// </summary>
        public static WebServer WebServer = new WebServer();

        public FormMain()
        {
            InitializeComponent();

            this.FormClosing += new FormClosingEventHandler(FormMain_FormClosing);

            web.Dock = System.Windows.Forms.DockStyle.Fill;
            //web.ScrollBarsEnabled = true;

            web.ObjectForScripting = this;
            //web.AllowWebBrowserDrop = false;//将 WebBrowser 控件的 AllowWebBrowserDrop 属性设置为 false，以防止 WebBrowser 控件打开拖放到其上的文件。
            //web.IsWebBrowserContextMenuEnabled = true;//将该控件的 IsWebBrowserContextMenuEnabled 属性设置为 false，以防止 WebBrowser 控件在用户右击它时显示其快捷菜单.
            //web.WebBrowserShortcutsEnabled = true;//将该控件的 WebBrowserShortcutsEnabled 属性设置为 false，以防止 WebBrowser 控件响应快捷键。
            //web.ScriptErrorsSuppressed = true;//将该控件的 ScriptErrorsSuppressed 属性设置为 true，以防止 WebBrowser 控件显示脚本代码问题的错误信息。 

            //web.Navigate("about:blank");

            web.Url = new Uri(string.Format(GlobalString.HTTP, GlobalString.PORT, "html/login.htm"));
            web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);

            this.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width,
                Screen.PrimaryScreen.WorkingArea.Height);
        }

        /// <summary>
        /// 加载完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                isShow = false;
                WebServer.Exit();
            }
            catch { }
        }

        /// <summary>
        /// 当前的数据库驱动
        /// </summary>
        public static IADO CurrentAdo = null;
        //是否显示窗口
        bool isShow = true;

        /// <summary>
        /// 测试连接并跳转到后台
        /// </summary>
        /// <param name="dbtype"></param>
        /// <param name="connectstring"></param>
        /// <returns></returns>
        public bool JsConnect(string dbtype, string connectstring)
        {
            connectstring = connectstring.Replace(">>>", "\\");
            dbtype = dbtype.Replace(">>>", "\\");
            CurrentAdo = ADO.CreateADO(new DBInfo { Type = dbtype.SS(), ConnectString = connectstring });

            //是否验证成功
            bool isSuccess = false;
            isShow = true;
            //这个线程容易死掉
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
            {
                int i = 1;
                while (isShow)
                {
                    DelegateFun.ExeControlFun(this, new DelegateFun.delegateExeControlFun(delegate
                    {
                        ExecuteJS("ShowDiv('正在验证数据库配置,请等待" + "".PadLeft(i, '.') + "');");
                    }));
                    if (i > 5) i = 1; else i++;
                    Thread.Sleep(400);
                }
            }));


            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
            {
                if (CurrentAdo.CheckState())
                {
                    DelegateFun.ExeControlFun(this, new DelegateFun.delegateExeControlFun(delegate
                    {
                        isShow = false;
                        ExecuteJS("ShowDiv('数据源测试通过,正在进入主界面!');");

                        isSuccess = true;
                    }));


                    Thread.Sleep(1000);
                }
                else
                {
                    DelegateFun.ExeControlFun(this, new DelegateFun.delegateExeControlFun(delegate
                    {
                        isShow = false;
                        ExecuteJS("ShowDiv('<font color=red>数据源测试不通过，请重新检查！</font>');");
                    }));


                    Thread.Sleep(3000);
                }

                DelegateFun.ExeControlFun(this, new DelegateFun.delegateExeControlFun(delegate
                {
                    isShow = false;
                    ExecuteJS("CloseDiv();");
                }));


                //打开新的页面...
                if (isSuccess) web.Url = new Uri(string.Format(GlobalString.HTTP, GlobalString.PORT, "html/main.htm"));
            }));

            return true;
        }

        /// <summary>
        /// 退出系统
        /// </summary>
        /// <returns></returns>
        public bool JsCloseWindows()
        {
            isShow = false;
            Application.Exit();
            return true;
        }

        /// <summary>
        /// 弹出验证框
        /// </summary>
        /// <param name="strValidate"></param>
        /// <returns></returns>
        public string JsOpenValidateWindow(string strValidate,string yaz)
        {
            strValidate = strValidate.Replace(">>>", "\\");
            FormValidate fv = new FormValidate(strValidate, yaz);
            fv.ShowDialog();

            return fv.Value;
        }

        public string JsFindFiles(string path)
        {
            path = path.Replace(">>>", "\\");

            string strFolder = Path.Combine(Application.StartupPath, path);
            string text = "";
            foreach (FileInfo fi in (new DirectoryInfo(strFolder)).GetFiles())
            {
                if (fi.Attributes != FileAttributes.Hidden)
                {
                    string name = fi.Name;
                    text += "|" + name;
                }
            }

            if (text.Length > 0) return text.Substring(1);
            return "";
        }

        //要缓存这部分值
        public static List<ColumnData> g_list = new List<ColumnData>();
        public static GlobalInfo g_globalinfo = new GlobalInfo();
        public static Dictionary<string, string> g_code = new Dictionary<string, string>();

        #region
        /// <summary>
        /// 字符串首字符大写
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static string UpperFirstChar(string inputStr)
        {
            string result = "";
            if (inputStr.Length >= 2)
            {
                string first = inputStr.Substring(0, 1);
                string last = inputStr.Substring(1, inputStr.Length - 1);
                result = first.ToUpper() + last;
            }
            else
            {
                result = inputStr.ToUpper();
            }
            return result;
        }

        /// <summary>
        /// 字符串首字符小写
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static string LowerFirstChar(string inputStr)
        {
            string result = "";
            if (inputStr.Length >= 2)
            {
                string first = inputStr.Substring(0, 1);
                string last = inputStr.Substring(1, inputStr.Length - 1);
                result = first.ToLower() + last;
            }
            else
            {
                result = inputStr.ToLower();
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 前台传递过来数据
        /// </summary>
        /// <param name="isCreate"></param>
        /// <param name="NameSpace"></param>
        /// <param name="FolderPath"></param>
        /// <param name="AuthorName"></param>
        /// <param name="ClassVersion"></param>
        /// <param name="ClassNameCN"></param>
        /// <param name="ckarr"></param>
        public void JsParseTable(string isCreate,string vmPath, string NameSpace, string FolderPath, string AuthorName, string ClassVersion, string ClassNameCN, string ckarr)
        {
            NameSpace = NameSpace.Replace(">>>", "\\");
            FolderPath = FolderPath.Replace(">>>", "\\");
            AuthorName = AuthorName.Replace(">>>", "\\");
            ClassVersion = ClassVersion.Replace(">>>", "\\");
            ClassNameCN = ClassNameCN.Replace(">>>", "\\");
            ckarr = ckarr.Replace(">>>", "\\");
            isCreate = isCreate.Replace(">>>", "\\");
            vmPath = vmPath.Replace(">>>", "\\");

            //var table = IHTMLTable
            //这里转换太BT了。要是能看懂，你就厉害了。
            IHTMLTable table = web.Document.InvokeScript("gettable") as IHTMLTable;

            int i = 0;
            //清除
            g_list.Clear();
            int index = 0;
            foreach (IHTMLTableRow o in table.rows)
            {
                if (i++ < 2) continue;

                ColumnData cd = new ColumnData();
                foreach (IHTMLElement j in o.cells)
                {
                    var key = j.getAttribute("atname");
                    if (key == null) throw new Exception("null");

                    var value = j.innerHTML;
                    object result = null;

                    if (key == "NameCN")
                    {
                        IHTMLDOMNode cell2Node = (IHTMLDOMNode)j;
                        IHTMLInputElement inputNode = cell2Node.childNodes.item(0) as IHTMLInputElement;
                        result = inputNode.value;
                    }
                    else if (key == "IsList" || key == "IsSearch" || key == "IsEdit" || key == "IsView")
                    {
                        if (value == "")
                        {
                            result = false;
                        }
                        else
                        {
                            IHTMLDOMNode cell2Node = (IHTMLDOMNode)j;
                            IHTMLInputElement inputNode = cell2Node.childNodes.item(0) as IHTMLInputElement;
                            result = inputNode.@checked;
                        }
                    }
                    else if (key == "IsIdentity" || key == "IsPK" || key == "IsNULL")
                    {
                        result = value == "√";
                        //设置主键
                        if (key == "IsPK" && value == "√") g_globalinfo.PK = UpperFirstChar(cd.Name);
                    }
                    else
                    {
                        if (cd.GetType().GetProperty(key).PropertyType == typeof(string)) result = value ?? "";
                        if (cd.GetType().GetProperty(key).PropertyType == typeof(int)) result = value.SI();
                        //if (cd.GetType().GetProperty(key).PropertyType == typeof(bool)) result = Convert.ToBoolean(value);
                    }

                    cd.GetType().GetProperty(key).SetValue(cd,
                        result, null);
                }

                g_list.Add(cd);
                //记录索引
                cd.Index = index++;
            }

            //根据操作继续往后执行
            g_globalinfo.FolderPath = FolderPath;
            g_globalinfo.ClassNameCN = ClassNameCN;
            g_globalinfo.ClassName = UpperFirstChar(g_globalinfo.TableName);
            g_globalinfo.NameSpace = UpperFirstChar(NameSpace);
            g_globalinfo.AuthorName = AuthorName;
            g_globalinfo.ClassVersion = ClassVersion;

            iniFile.key_namespace = g_globalinfo.NameSpace;
            iniFile.key_namecn = g_globalinfo.ClassNameCN;
            iniFile.key_path = g_globalinfo.FolderPath;
            iniFile.key_user = g_globalinfo.AuthorName;
            iniFile.key_ver = g_globalinfo.ClassVersion;
            //保存配置
            iniFile.Save();

            //动态创建tab并显示
            ViewTemplate.InitViewTemplate(vmPath);

            foreach (string s in ckarr.Replace(" ", "").Split('|'))
            {
                try
                {
                    string code = ViewTemplate.ParseVm(s); 
                    g_code[s.ToUpper()] = code;
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
            //生成文件
            if (isCreate == "1")
            {
                foreach (string s in ckarr.Replace(" ", "").Split('|'))
                {
                    string strRoot = g_globalinfo.FolderPath;// +"\\" + g_globalinfo.NameSpace;
                    SafeCreateDirectory(strRoot);

                    if (s.ToLower().EndsWith("vm"))
                    {
                        string vmPathChildren = strRoot + "\\" + g_globalinfo.NameSpace;
                        SafeCreateDirectory(vmPathChildren);
                        vmPathChildren = vmPathChildren + "\\" + g_globalinfo.ClassName;
                        SafeCreateDirectory(vmPathChildren);

                        //生成文件
                        CreateFile(s.ToUpper(), s.ToLower(), vmPathChildren);

                        continue;
                    }

                    if (s.ToLower().EndsWith(".hbm.xml"))
                    {
                        string modelPath = strRoot + "\\Models";
                        SafeCreateDirectory(modelPath);

                        //生成文件
                        CreateFile(s.ToUpper(), g_globalinfo.ClassName + ".hbm.xml", modelPath);
                        continue;
                    }

                    if (s.ToLower().EndsWith("model.cs"))
                    {
                        string modelPath = strRoot + "\\Models";
                        SafeCreateDirectory(modelPath);

                        //生成文件
                        CreateFile(s.ToUpper(), g_globalinfo.ClassName + ".cs", modelPath);
                        continue;
                    }

                    if (s.ToLower().EndsWith("controller.cs"))
                    {
                        string controllerPath = strRoot + "\\Controllers";
                        SafeCreateDirectory(controllerPath);

                        //生成文件
                        CreateFile(s.ToUpper(), g_globalinfo.ClassName + "Controller.cs", controllerPath);
                        continue;
                    }

                    //生成其他文件
                    CreateFile(s.ToUpper(), s, strRoot);
                }
            }

            //下面要接着解析
            //MessageBox.Show("代码生成完毕!");
            JsShowCode();
        }

        IniFile iniFile = new IniFile();

        void CreateFile(string p, string s, string strRoot)
        {
            string path = Path.Combine(strRoot, s);
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter writer = new StreamWriter(path, false, Encoding.Default))
            {
                writer.Write(g_code[p]);
                writer.Flush();
                writer.Close();
            }
        }

        void SafeCreateDirectory(string path)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string JsSelectPath(string path)
        {
            path = path.Replace(">>>", "\\");
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.SelectedPath = path;

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = fbd.SelectedPath;
            }

            return path;
        }

        /// <summary>
        /// 显示代码
        /// </summary>
        /// <param name="page"></param>
        public void JsShowCode()
        {
            if (g_code.Count > 0)
            {
                FormShowCode fsc = new FormShowCode();
                //fsc.Value = WebProcessing.__vm(page);
                fsc.Size = this.Size;
                fsc.ShowDialog();
            }
            else
            {
                MessageBox.Show("请先生成文件再预览!");
            }
        }

        /// <summary>
        /// 执行JS方法
        /// </summary>
        /// <param name="script"></param>
        void ExecuteJS(string script)
        {
            if (web.Document != null)
                web.Document.InvokeScript("WinJS", new string[] { script });
        }
    }
}
